package com.example.luyennghe;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.luyennghe.DsBaiNgheActivity.BaingheHolder;

public class DsBaiTestTracNghiemActivity extends Activity {
    private UserInfo user = new UserInfo();    
    private Bundle extras;
    private ArrayList<BaiTest> baiTestArraylist = new ArrayList<BaiTest>();    
    private BaiTest baiTest;
    private ProgressDialog pDialog;
    private JSONParser jParser = new JSONParser();
    private static String urlDsBaiTest = "http://huynh.cu.cc/android-server/get_ds_baitest.php";
    private static String urlUserData = "http://huynh.cu.cc/android-server/get_userdata.php";
    private static String urlAddRemoveBookmark = "http://huynh.cu.cc/android-server/bookmark.php";
    private int clickedIndex = 0;       //stt item o vi tri duoc click trong listview
    private String bookmark = "";
    private String danhMuc = "";
    
    private boolean insertedBookmarkSuccess = false;
    private boolean deletedBookmarkSuccess = false;
    private boolean errorConnectDatabase = false;
    private boolean noTestFound = false;
    private boolean loadDsSuccess = false;
    
    JSONArray dsbainghe = new JSONArray();
    //JSON node
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_DSBAITEST = "dsbaitest";
    private static final String TAG_ID = "id";
    private static final String TAG_STT = "stt";
    private static final String TAG_DANHMUC = "danhmuc";     

    private static final String TAG_USERDATA = "userdata";
    private static final String TAG_BOOKMARK = "bookmark";
    private static final String TAG_DALAM = "dalam";
    private static final String TAG_DIEM = "diem";
    private static final String TAG_NGAYLAM = "ngaylam";
    
    public ListView lvDSBaiTest;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dsbaitesttracnghiem_layout);
        lvDSBaiTest = (ListView)findViewById(R.id.lvDsBaiTest);        
        //lay thong tin user        
        extras = getIntent().getExtras();
        if (extras != null) {
            user = (UserInfo)extras.getSerializable("userinfo");
            danhMuc = extras.getString("danhmuc");
            Log.d("capdo: ", danhMuc);            
        }
        else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiTestTracNghiemActivity.this);
            builder.setTitle("Lỗi")
                    .setMessage("Có lỗi xảy ra. Hãy thử lại sau.")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }                
        loadBaiTestHandler();
    }    
    
    public class BaiTestAdapter extends ArrayAdapter<BaiTest>{
        String yes = "yes";
        BaiTest baiTest = null;
        Context context;
        int layoutResourceId;   
        ArrayList<BaiTest> data = null;        
       
        public BaiTestAdapter(Context context, int layoutResourceId, ArrayList<BaiTest> data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            baiTest = data.get(position);
            BaingheHolder holder = null;
           
            if(row == null)
            {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(layoutResourceId, parent, false);
               
                holder = new BaingheHolder();
                holder.tvDiem = (TextView)row.findViewById(R.id.tvDiem);
                holder.stt = (TextView)row.findViewById(R.id.stt);
                holder.tvNgaylam = (TextView)row.findViewById(R.id.tvNgaylam);
                holder.imgBookmark = (ImageButton)row.findViewById(R.id.imgBookmark);
                holder.imgDalam = (ImageButton)row.findViewById(R.id.imgDalam);  
                //dat tag la position (index item)
                holder.imgBookmark.setTag(position);
                //dat tag la id bai test
                holder.imgDalam.setTag(baiTest.getId());
                row.setTag(holder);
            }
            else
            {
                holder = (BaingheHolder)row.getTag();
            }     
            if(yes.equals(baiTest.getBookmark())){
                holder.imgBookmark.setBackgroundResource(R.drawable.bookmarked);
            }
            else    
                holder.imgBookmark.setBackgroundResource(R.drawable.none_bookmark);
            if(yes.equals(baiTest.getDaLam())){
                holder.imgDalam.setVisibility(View.VISIBLE);
                holder.tvDiem.setText(baiTest.getDiem() + " điểm");
                holder.tvNgaylam.setText("Vào lúc " + baiTest.getNgayLam());
                holder.tvDiem.setVisibility(View.VISIBLE);
                holder.tvNgaylam.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.imgDalam.setVisibility(View.INVISIBLE);
                holder.tvDiem.setVisibility(View.INVISIBLE);
                holder.tvNgaylam.setVisibility(View.INVISIBLE);
            }           
            
            holder.stt.setText(baiTest.getStt());
            holder.imgBookmark.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //lay position cua item 
                    int which = -1;
                    Object obj =  v.getTag();                   
                    if(obj instanceof Integer){
                        which = ((Integer)obj).intValue();
                    }
                    if (which > -1) {
                        clickedIndex = which;
                    }
                    
                    View view = lvDSBaiTest.getChildAt(clickedIndex - lvDSBaiTest.getFirstVisiblePosition());
                    ImageButton imgdalam = (ImageButton)view.findViewById(R.id.imgDalam);
                    
                    //lay id bai test
                    String id = "";
                    Object id_obj = imgdalam.getTag();
                    if(id_obj instanceof String){
                        id = id_obj.toString();
                    }
                    if (!id.equals("")) {
                        bookmark = id;
                    }                                       
                    bookmarkHandler();
                }
            });
            return row;
        }   
    }
    public static class BaiTestHolder {
        TextView stt;
        TextView tvDiem;
        TextView tvNgaylam;
        ImageButton imgBookmark;
        ImageButton imgDalam;
    }
    //them/xoa bookmark
    class AddRemoveBookmark extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();            
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters            
            List<NameValuePair> paramsAddbookmark = new ArrayList<NameValuePair>();
            paramsAddbookmark.add(new BasicNameValuePair("username", user.getUsername()));   
            paramsAddbookmark.add(new BasicNameValuePair("bainghe", bookmark)); 
            JSONObject json = new JSONObject();
            // getting JSON string from URL
            try {               
                //gui du lieu len server
                json = jParser.makeHttpRequest(urlAddRemoveBookmark, "POST",
                        paramsAddbookmark);
                Log.d("bookmark: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString("message");
                if (success == 1 && mes.equals("Inserted")) {
                    insertedBookmarkSuccess = true;
                }
                else
                    if (success == 1 && mes.equals("Deleted")) {
                        deletedBookmarkSuccess = true;
                    }
                    else
                    {
                        errorConnectDatabase = true;
                    }   
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            if(insertedBookmarkSuccess){
                insertedBookmarkSuccess = false;
                View v = lvDSBaiTest.getChildAt(clickedIndex - lvDSBaiTest.getFirstVisiblePosition());
                ImageButton imgbookmark = (ImageButton)v.findViewById(R.id.imgBookmark);
                imgbookmark.setBackgroundResource(R.drawable.bookmarked);
                Toast.makeText(getApplicationContext(), "Đã bookmark bài nghe", Toast.LENGTH_SHORT).show();
            }
            else 
                if(deletedBookmarkSuccess){
                    deletedBookmarkSuccess = false;
                    View v = lvDSBaiTest.getChildAt(clickedIndex - lvDSBaiTest.getFirstVisiblePosition());
                    ImageButton imgbookmark = (ImageButton)v.findViewById(R.id.imgBookmark);
                    imgbookmark.setBackgroundResource(R.drawable.none_bookmark);
                    Toast.makeText(getApplicationContext(), "Đã xóa bookmark bài nghe", Toast.LENGTH_SHORT).show();
                }
                else 
                    if(errorConnectDatabase){
                        errorConnectDatabase = false;
                        AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiTestTracNghiemActivity.this);
                        builder.setTitle("Lỗi")
                               .setMessage("Không thể kết nối đến database. Vui lòng thử lại sau.")
                               .setCancelable(false)
                               .setIcon(R.drawable.warning_icon)
                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       dialog.dismiss();
                                   }
                               });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
        }
    }
    public void bookmarkHandler(){              
        final AddRemoveBookmark ar_bm = new AddRemoveBookmark();
        ar_bm.execute();    
        Handler _handler = new Handler();
        _handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ar_bm.getStatus() == AsyncTask.Status.RUNNING) {
                    ar_bm.cancel(true);
                    pDialog.dismiss();
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            DsBaiTestTracNghiemActivity.this);
                    builder.setMessage(
                            "Không thể kết nối đến server. Xin hãy thử lại.")
                            .setCancelable(false)
                            .setTitle("Lỗi")
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối được.
    }
    
    class LoadBaiTest extends AsyncTask<String, String, String> {
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DsBaiTestTracNghiemActivity.this);
            pDialog.setMessage("Đang tải danh sách bài nghe. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> paramsDSbaitest = new ArrayList<NameValuePair>();
            paramsDSbaitest.add(new BasicNameValuePair("danhmuc", danhMuc));
            
            List<NameValuePair> paramsUserdata = new ArrayList<NameValuePair>();
            paramsUserdata.add(new BasicNameValuePair("username", user.getUsername()));   
            Log.d("username: ", user.getUsername());
            JSONObject json = new JSONObject();
            String mes;
            // getting JSON string from URL
            try {
                //lay danh sach bai nghe
                json = jParser.makeHttpRequest(urlDsBaiTest, "GET",
                        paramsDSbaitest);

                // Check your log cat for JSON reponse
                Log.d("DS bài nghe: ", json.toString());
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    loadDsSuccess = true;
                    dsbainghe = json.getJSONArray(TAG_DSBAITEST);
                    for (int i = 0; i < dsbainghe.length(); i++) {
                        JSONObject c = dsbainghe.getJSONObject(i);
                        BaiTest temp = new BaiTest();
                        temp.setStt(c.getString(TAG_STT));
                        temp.setDanhMuc(c.getString(TAG_DANHMUC));
                        temp.setId(c.getString(TAG_ID));
                        baiTestArraylist.add(temp);
                    }
                } 
                else 
                {
                    if(success==0 && mes.equals("No lesson found"))
                        noTestFound = true;
                    else
                        if(success==0 && mes.equals("Can't connect to database"))
                            errorConnectDatabase = true;
                }
                //lay du lieu cua nguoi dung
                json = jParser.makeHttpRequest(urlUserData, "GET",
                        paramsUserdata);
                Log.d("Userdata: ", json.toString());
                // Check SUCCESS TAG
                success = json.getInt(TAG_SUCCESS);
                mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    JSONArray userdata = json.getJSONArray(TAG_USERDATA);
                    if(userdata.length()>0)
                    {
                        for (int i = 0; i < userdata.length(); i++) {
                            JSONObject c = userdata.getJSONObject(i);
    
                            // Storing each json item in variable
                            String bookmark = c.getString(TAG_BOOKMARK);
                            String dalam = c.getString(TAG_DALAM);
                            String diem = c.getString(TAG_DIEM);
                            String ngaylam = c.getString(TAG_NGAYLAM);
                            for (int j = 0; j < baiTestArraylist.size(); j++) {
                                if (baiTestArraylist.get(j).getId().equals(bookmark)) {
                                    baiTestArraylist.get(j).setBookmark("yes");
                                }
                                if (baiTestArraylist.get(j).getId().equals(dalam)) {
                                    baiTestArraylist.get(j).setDaLam("yes");
                                    baiTestArraylist.get(j).setDiem(diem);
                                    baiTestArraylist.get(j).setNgayLam(ngaylam);
                                }
                            }
                        }
                    }                   
                }
                else if (success == 0 && mes.equals("Can't connect to database"))
                    errorConnectDatabase = true;

            } catch (Exception ex) {
                /*AlertDialog.Builder builder = new AlertDialog.Builder(
                        DsBaiNgheActivity.this);
                builder.setMessage(
                        "Không thể tải dữ liệu từ server. Xin hãy thử lại.")
                        .setCancelable(false)
                        .setTitle("Lỗi")
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        dialog.dismiss();
                                        finish();
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();*/
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            if(loadDsSuccess)
            {
                loadDsSuccess = false;
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        BaiTestAdapter adapter = new BaiTestAdapter(getApplicationContext(), R.layout.baitesttracnghiem_item, baiTestArraylist);
                        lvDSBaiTest.setClickable(true);
                        lvDSBaiTest.setOnItemClickListener(new OnItemClickListener() {
                         
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                                clickedIndex = position;
                                baiTest = baiTestArraylist.get(position);
                                // Starting new intent
                                Intent in = new Intent(getApplicationContext(),
                                        NgheActivity.class);
                                // sending data to next activity
                                in.putExtra("baitest", baiTest);
                                in.putExtra("userinfo", user);
                                startActivity(in);

                            }
                        });      
                        lvDSBaiTest.setAdapter(adapter);
                    }
                });
            }
            else
                if(noTestFound){
                    noTestFound = false;
                    Toast.makeText(getApplicationContext(), "Khong tim thay bai test nao.", Toast.LENGTH_SHORT).show();
                }
                else
                    if(errorConnectDatabase){
                        errorConnectDatabase = false;
                        Toast.makeText(getApplicationContext(), "Khong the ket noi den database.", Toast.LENGTH_SHORT).show();
                    }
 
        }
    }
    public void loadBaiTestHandler(){
        final LoadBaiTest loadDsBaiTest = new LoadBaiTest();        
        try{            
            loadDsBaiTest.execute();
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (loadDsBaiTest.getStatus() == AsyncTask.Status.RUNNING) {
                        loadDsBaiTest.cancel(true);
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                DsBaiTestTracNghiemActivity.this);
                        builder.setMessage(
                                "Kết nối quá thời gian... Xin hãy thử lại.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setTitle("Lỗi")
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                finish();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }

                }
            }, 30000); // timeout sau...giây sẽ hiện thông báo không kết nối
                        // được.
        }
        catch (Exception ex)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiTestTracNghiemActivity.this);
            builder.setMessage(
                    "Không thể tải dữ liệu từ server. Xin hãy thử lại.")
                    .setCancelable(false)
                    .setTitle("Lỗi")
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }       
    }
}
